<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="1">
        <el-col :span="6">
          <el-form-item label="实验编号" prop="experimentNo">
            <el-input
              v-model="queryParams.experimentNo"
              placeholder="请输入实验编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="样品编号" prop="sampleNo">
            <el-input
              v-model="queryParams.sampleNo"
              placeholder="请输入实验名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="材料" prop="materialId">
              <el-select v-model="queryParams.materialId" placeholder="请选择材料" @change="matChange">
                <el-option
                  v-for="item in matList"
                  :key="item.id"
                  :label="item.matName"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.matName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.matNo }}</span>
                </el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实验人员" prop="experimentPersons">
            <el-select v-model="queryParams.experimentPersons"  placeholder="请选择人员">
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="`${item.userName}-${item.nickName}`"
                :value="item.userId"
              >
                <span style="float: left">{{ item.userName }}</span>
                <span style="color: #8492a6; font-size: 13px">{{ item.nickName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dept.deptName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="1">
        <el-col :span="12">
          <el-form-item label="查询参数" prop="vjson">
            <search-condition :value="vjsonq"></search-condition>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实验时间">
            <el-date-picker
              v-model="daterangeExperimentTime"
              
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>  
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hustmed:sample:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hustmed:sample:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hustmed:sample:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hustmed:sample:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" 
      :data="experimentList"
      @selection-change="handleSelectionChange"  
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="实验id" align="center" prop="id" /> -->
      <el-table-column label="实验编号" align="center" prop="experimentNo" />
      <el-table-column label="样品编号" align="center" prop="sampleNo" />
      <!-- <el-table-column label="实验名称" align="center" prop="name" /> -->
      <el-table-column label="材料" align="center" prop="material.matName" >
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.material.matName }}</span>
          <span style="margin-left: 10px">{{ scope.row.material.matNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工艺类型" align="center" prop="process" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.process_type" :value="scope.row.process"/>
        </template>
      </el-table-column>
      <el-table-column label="计划时间" align="center" prop="experimentTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.experimentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实验人员" align="center" prop="experimentPersons" >
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper" style="padding:2px" v-for="item in scope.row.sysUsers" :key="item.userId">
            <el-tag size="medium">{{ item.nickName }}-{{ item.userName }}</el-tag>
          </div>
        </template>
      </el-table-column> 
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.experiment_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user" :value="scope.row.createBy"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="更新者" align="center" prop="updateBy" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user" :value="scope.row.updateBy"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hustmed:sample:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hustmed:sample:remove']"
          >删除</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleView(scope.row)"
            v-hasPermi="['hustmed:sample:query']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改实验对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body :key="dialogKey" @close="diaClose" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="!editMode">
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="实验编号" prop="experimentNo">
              <el-input v-model="form.experimentNo" placeholder="请输入实验编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实验名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入实验名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工艺类别" prop="process">
              <!-- <el-input v-model="form.process" placeholder="请输入工艺类别" /> -->
              <el-select
              v-model="form.process"
              placeholder="请输入工艺类别"
              
              :disabled=true
            >
              <el-option
                v-for="dict in dict.type.process_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="材料" prop="materialId">
              <el-select v-model="form.materialId" placeholder="请选择材料" @change="matChange">
                <el-option
                  v-for="item in matList"
                  :key="item.id"
                  :label="item.matName"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.matName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.matNo }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实验人员" prop="experimentPersons">
              <el-select v-model="form.experimentPersons"  multiple placeholder="请选择人员">
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="`${item.dept.deptName}-${item.userName}-${item.nickName}`"
                  :value="item.userId"
                >
                  <span style="float: left">{{ item.userName }}</span>
                  <span style="color: #8492a6; font-size: 13px">{{ item.nickName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dept.deptName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实验日期" prop="experimentTime">
              <el-date-picker
                v-model="form.experimentTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="16">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" rows="1" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实验状态" prop="status">
              <!-- <el-input v-model="form.process" placeholder="请输入工艺类别" /> -->
              <el-select
                v-model="form.status"
                placeholder="请选择实验状态"
                
              >
                <el-option
                  v-for="dict in dict.type.experiment_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-collapse v-model="activeCollapseName" >
        <el-collapse-item title="材料" name="1">
           <!-- 材料模版数据展示 -->
           <tt ref="matTemp" 
            :masterData="this.matData" 
            :edit="editTemplate"
            :key="matTemplateKey"
            :templateEditable="true"
            >
          </tt>
        </el-collapse-item>
        <el-collapse-item title="工艺参数" name="2">
          <!-- <div style="margin-bottom: 10px;margin-top: 10px;">
            <el-button type="warning" plain size="small" @click="addProcessParamsTab(processParamsTabsValue)">
              添加参数组
            </el-button>
          </div> -->
          <el-tabs v-model="processParamsTabsValue" type="card" 
            closable 
            @tab-remove="removeProcessParamsTab" 
            @tab-click ="processParamsTabClick"
            :key="processParamsTabsKey" >
            <el-tab-pane
              v-for="(item, index) in processParamsTabs"
              :key="item.tabKey"
              :label="item.title"
              :name="item.name"
            >
              <tt ref="processTemp" 
                :masterData="item" 
                :templateType="1"
                :templateId="templateId" 
                :edit="editTemplate"
                :templateEditable="!editMode"
                :key="item.ttKey">
              </tt>
              <!-- <div style="margin-bottom: 10px;margin-top: 10px;">
                <el-button type="warning" plain size="small" @click="addSampleTab(item)"  >
                  添加样品数据
                </el-button>
              </div> -->
            </el-tab-pane>
          </el-tabs>
        </el-collapse-item>
        <el-collapse-item title="样品" name="3">
          <el-tabs v-model="sampleTabsValue" type="card" closable @tab-remove="removeSampleTab" :key="sampleTabsKey">
            <el-tab-pane
              v-for="(item) in curSTab"
              :key="item.tabKey"
              :label="item.title"
              :name="item.name"
            >
              <el-form  ref="sampleform" :model="item"  label-width="80px" :disabled="!editMode">
                <el-row :gutter="1">
                  <el-col :span="8">
                    <el-form-item label="样品编号" prop="experimentNo">
                      <el-input v-model="item.sampleNo" placeholder="请输样品编号" @input="force" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="样品名称" prop="sampleName">
                      <el-input v-model="item.sampleName" placeholder="请输入样品名称"  @input="force" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="备注" prop="remark">
                      <el-input v-model="item.sampleRemark" placeholder="备注"  @input="force"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <tt ref="sampleTemp" 
                :masterData="item" 
                :templateType="3"
                :templateEditable="!editMode"
                :key="item.ttKey">
              </tt>
            </el-tab-pane>
          </el-tabs>
        </el-collapse-item>
      </el-collapse>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="editMode" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExperiment, getExperiment, delExperiment, addExperiment, updateExperiment ,sampleList} from "@/api/hustmed/experiment";
import {  listMaterial,  getMaterial,  delMaterial,  addMaterial,  updateMaterial} from "@/api/hustmed/material";
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";
import tt from '@/components/Template'
import searchCondition from '@/components/SearchCondition'
export default {
  name: "Experiment",
  dicts: ['experiment_status', 'del_flag','user','process_type'],
  components:{
    tt,
    searchCondition
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实验表格数据
      experimentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogKey:1,
      processParamsTabsKey:1,
      sampleTabsKey:1,
      matTemplateKey:1,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialId: null,
        name: null,
        process: null,
        experimentNo: null,
        experimentPersons: null,
        status: null,
      },
      matList:[],
      userList:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialId: [
          { required: true, message: "材料id不能为空", trigger: "blur" }
        ],
        
        experimentPersons: [
          { required: true, message: "实验人员不能为空", trigger: "blur" }
        ],
        experimentTime: [
          { required: true, message: "实验时间不能为空", trigger: "blur" }
        ]
      },
      globalKey:1,
      editTemplate:false,
      //process params标签页
      processParamsTabsValue: 0,
      processParamsTabs: [],
      processParamsTabsIndex: 0,
      templateId:this.$route.query.templateId,
      //sample标签页
      vjsonq:[],
      matData:[],
      //json 数据
      paramList:[],
      editMode:true,
      sampleTabs:{},
      sampleTabsValue:'1',
      sampleTabsIndex:1,
      curSTab:[],

      activeCollapseName:'3',
      daterangeExperimentTime: [],

    };
  },
  created() {
    this.getList();
    this.getMatList()
    this.getPersonList()
  },

  methods: {
    /** 查询实验列表 */
    getList() {
      this.loading = true;
      this.queryParams.process = this.$route.query.processType
      this.queryParams.experimentNo = this.queryParams.experimentNo? this.queryParams.experimentNo:this.$route.query.experimentNo
      this.queryParams.params = {}
      if (null != this.daterangeExperimentTime && '' != this.daterangeExperimentTime) {
        this.queryParams.params["beginExperimentTime"] = this.daterangeExperimentTime[0]
        this.queryParams.params["endExperimentTime"] = this.daterangeExperimentTime[1]
      }
      sampleList(this.queryParams).then(response => {

        this.experimentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getMatList() {
      this.loading = true;
      let queryParams = {}
      queryParams.status=1
      listMaterial(queryParams).then(response => {
        this.matList = response.rows;
        this.loading = false;
      });
    },

    getPersonList() {
      this.loading = true;
      let queryParams = {}
      queryParams.status=0
      listUser(queryParams).then(response => {
          this.userList = response.rows;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        materialId: null,
        name: null,
        process: null,
        experimentNo: null,
        experimentPersons: null,
        remark: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.dialogKey = ++this.globalKey
      this.processParamsTabsKey = ++this.globalKey
      this.sampleTabsKey = ++this.globalKey
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.vjsonq = this.resolveVjsonQuery1()
      this.getList();
    },
    resolveVjsonQuery1(){
      if(this.vjsonq.length>0){
        let str = ''
        let reg1 = /\s+/g
        this.vjsonq.map(i=>{
          if(i.attr!='' && i.opera!='' && i.val!=''){
            str+= `(CONVERT(p.vjson->'$."`+i.attr.replace(reg1,'')+`"',decimal(10,3)) `+i.opera+i.val +' or '+`CONVERT(s.vjson->'$."`+i.attr.replace(reg1,'')+`"',decimal(10,3)) `+i.opera+i.val +') and '
          }
        })
        return str+'1=1'
      }else{
        return ''
      }
    },
    resolveVjsonQuery2(){
      if(this.queryParams.vjson){
        let reg1 = /\s+/g
        let reg2 = /[\u4E00-\u9FA5]+/g
        let reg3 = /and/g
        let result = this.queryParams.vjson.replace(reg1,'')
          .replace(reg3,(match)=>{return ` ${match} `})
          .replace(reg2,(match)=>{ return ` CONVERT(vjson->'$."${match}"',decimal(10,3)) `})
        return result
      }else{
        return this.queryParams.vjson
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.vjsonq=[]
      this.daterangeExperimentTime=[]
      this.handleQuery();
    },
    
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      ++this.matTemplateKey
      this.matData=[]
      this.open = true;
      this.title = "添加实验";
      this.processParamsTabsValue='1'
      this.editTemplate=false
      
      this.processParamsTabs= [{
        title: 'params Tab1',
        name: '1',
        tabKey: ++this.globalKey,
        ttKey: ++this.globalKey,
        cjson:'[]',
        sampleTabsValue: '1',
        sampleTabs: [{
          title: 'sample Tab1',
          name: '1',
          tabKey: ++this.globalKey,
          ttKey: ++this.globalKey,
          cjson:'[]',
        }],
        sampleTabsIndex: 1,
      }],
      this.processParamsTabsIndex=1,
      this.form.process = this.$route.query.processType
    },
    handleView(row){
      this.reset();
      this.editMode =false
      const id = row.id || this.ids
      ++this.matTemplateKey
      getExperiment(id).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.form.experimentPersons = this.form.experimentPersons.split(',').map(i=>{return parseInt(i)})
        this.form.status = String(this.form.status)
        let data = response.data
        this.editTemplate = true

        this.processParamsTabs = []
        this.matData =  this.matData = this.matList.filter(i=>i.id==this.form.materialId)[0]
        
        data.processParamsList.forEach((p,index)=>{
          let pobj = {}
          pobj.title=p.processParamsNo
          pobj.id = p.id
          pobj.name = p.id
          pobj.tabKey = ++this.globalKey
          pobj.ttKey = ++this.globalKey
          pobj.cjson = p.cjson
          pobj.sampleTabsValue='1'
          pobj.sampleTabsIndex = p.sampleList.length
          pobj.sampleTabs = []
          this.sampleTabs[p.id] = []
          p.sampleList.forEach((s,index)=>{
            let sobj = {}
            sobj.title= s.sampleNo
            sobj.id = s.id
            sobj.name = String(index+1)
            sobj.tabKey = ++this.globalKey
            sobj.ttKey = ++this.globalKey
            sobj.sampleName = s.name
            sobj.sampleNo = s.sampleNo
            sobj.sampleRemark = s.remark
            sobj.cjson = s.cjson
            this.sampleTabs[p.id].push(sobj)
          })
          this.processParamsTabs.push(pobj)
        })
       
        this.processParamsTabsValue=this.processParamsTabs[0].id
        this.processParamsTabsIndex=1
        let curPTabName = this.processParamsTabs[0].name
        this.curSTab = this.sampleTabs[curPTabName]
        
        this.open = true
        // this.globalKey = +this.globalKey
        this.title = "样品查询"
      });
      
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      ++this.matTemplateKey
      getExperiment(id).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.form.experimentPersons = this.form.experimentPersons.split(',').map(i=>{return parseInt(i)})
        this.form.status = String(this.form.status)
        let data = response.data
        this.editTemplate = true
        this.processParamsTabsValue='1'
        this.processParamsTabsIndex=data.processParamsList.length
        this.processParamsTabs = []
        this.matData =  this.matData = this.matList.filter(i=>i.id==this.form.materialId)[0]
        data.processParamsList.forEach((p,index)=>{
          let pobj = {}
          pobj.title="params Tab"+(index+1)
          pobj.id = p.id
          pobj.name = String(index+1)
          pobj.tabKey = ++this.globalKey
          pobj.ttKey = ++this.globalKey
          pobj.cjson = p.cjson
          pobj.sampleTabsValue='1'
          pobj.sampleTabsIndex = p.sampleList.length
          pobj.sampleTabs = []
          p.sampleList.forEach((s,index)=>{
            let sobj = {}
            sobj.title= 'sample Tab'+(index+1)
            sobj.id = s.id
            sobj.name = String(index+1)
            sobj.tabKey = ++this.globalKey
            sobj.ttKey = ++this.globalKey
            sobj.cjson = s.cjson
            pobj.sampleTabs.push(sobj)
          })
          this.processParamsTabs.push(pobj)
        })
        
        this.open = true
        // this.globalKey = +this.globalKey
        this.title = "样品查询"
      });
    },

/** tab页 */
    addProcessParamsTab(targetName) {
      let newTabName = ++this.processParamsTabsIndex + '';
      this.processParamsTabs.push({
        title: 'params Tab'+newTabName,
        name: newTabName,
        key: ++this.globalKey,
        cjson:'[]',
        sampleTabsValue: '1',
        sampleTabs: [{
          title: 'sample Tab1',
          name: '1',
          key: ++this.globalKey,
          cjson:'[]',
        }],
        sampleTabsIndex: 1,
      });
      this.processParamsTabsValue = newTabName;
    },
    removeProcessParamsTab(targetName) {
      let tabs = this.processParamsTabs;
      let activeName = this.processParamsTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.processParamsTabsValue = activeName;
      this.processParamsTabs = tabs.filter(tab => tab.name !== targetName);
    },
    force(val){
      this.$forceUpdate()
    },
    processParamsTabClick(targetTab){
      this.sampleTabsValue='1',
      this.sampleTabsIndex=1,
      this.curSTab = this.sampleTabs[targetTab.name]
     
    },
    addSampleTab(item) {
      item.sampleTabsValue
      let newTabName = ++item.sampleTabsIndex + '';
      item.sampleTabs.push({
        title: 'sample Tab'+newTabName,
        name: newTabName,
        key: ++this.globalKey,
        cjson:'[]',
      });
      item.sampleTabsValue = newTabName;
    },
    removeSampleTab(targetName) {

      let pTabs = this.processParamsTabs
      let pTabName = this.processParamsTabsValue
      let item = pTabs.filter(tab => tab.name==pTabName)[0]
      let tabs = item.sampleTabs;
      let activeName = item.sampleTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      item.sampleTabsValue = activeName;
      item.sampleTabs = tabs.filter(tab => tab.name !== targetName);
    },
    /** 提交按钮 */
    submitForm() {
      // console.log('this.$refs.processTemp::',this.$refs.processTemp)
      this.$refs.processTemp.forEach(i=>{i.save()})
      this.$refs.sampleTemp.forEach(i=>{i.save()})
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.experimentPersons = this.form.experimentPersons.join()
          this.form.cjson = JSON.stringify(this.resolveJson(this.processParamsTabs) )
          if (this.form.id != null) {   
            updateExperiment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // console.log(this.form.experimentPersons)
            addExperiment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    resolveJson(){

      let pdata = this.processParamsTabs
      let result =[]
      pdata.forEach(i=>{
        let param ={}
        param.cjson = i.cjson
        param.vjson = i.vjson
        param.id = i.id
        param.samples =[] 
        let sdata = i.sampleTabs
        sdata.forEach(j=>{
          let sample ={}
          sample.cjson = j.cjson
          sample.vjson = j.vjson
          sample.id = j.id
          param.samples.push(sample)
        })
        result.push(param)
      })
      // for(i in pdata){
      //   let param ={}
      //   param.cjson = pdata[i].cjson
      //   param.samples =[] 
      //   let sdata = pdata[i].sampleTabs
      //   for(j in sdata){
      //     param.samples.push(sdata[j].cjson)
      //   }
      //   result.push(param)
      // }
      return result
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const experimentNos = row.experimentNo || this.experimentNos;
      this.$modal.confirm('是否确认删除实验编号为"' + experimentNos + '"的数据项？').then(function() {
        return delExperiment(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hustmed/experiment/export', {
        ...this.queryParams
      }, `experiment_${new Date().getTime()}.xlsx`)
    },
    matChange(val){
      if(val){
        this.matTemplateKey=+new Date()
        this.matData = this.matList.filter(i=>i.id==val)[0]
        // this.drawingList = JSON.parse(templateObj[0].cjson)
      }
    },
    diaClose(){
      this.activeCollapseName='3'
    }
  }
};
</script>

<style lang='scss'>
.tab-padding {
  padding-top: 1vh;
  
}
</style>